// 加载已存在的PDF
function loadPdf(url) {
    return new Promise((resolve, reject) => {
        // 加载PDF文档
        var loadingTask = pdfjsLib.getDocument(url);
        loadingTask.promise.then(function(pdf) {
            resolve(pdf);
        }, function (reason) {
            // PDF加载出错
            reject(reason);
        });
    });
}

// 渲染PDF页面并高亮关键字
async function renderPageWithHighlight(pdf, pageNumber, scale, keyword) {
    const page = await pdf.getPage(pageNumber);
    const viewport = page.getViewport({ scale: scale });

    // 准备canvas元素
    const canvas = document.getElementById('pdf-canvas');
    const context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    // 渲染PDF页面到canvas
    const renderContext = {
        canvasContext: context,
        viewport: viewport
    };
    const renderTask = page.render(renderContext);

    // 等待页面渲染完成
    renderTask.promise.then(function () {
        // 在这里添加高亮关键字的代码
        highlightText(context, keyword, viewport);
    });
}

// 在canvas上高亮文本
function highlightText(context, keyword, viewport) {
    const items = textContent.items;
    const quads = [];
    let textItems = [];

    // 遍历文本项并收集四边形和文本
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (!item.str || !item.transform) {
            continue;
        }
        quads.push(item.quad);
        textItems.push(item.str);
    }

    // 合并文本项
    const fullText = textItems.join(' ');

    // 搜索关键字
    const regex = new RegExp(keyword, 'gi');
    let match;
    let startIndex = 0;
    const highlights = [];

    // 匹配所有关键字实例
    while ((match = regex.exec(fullText)) !== null) {
        const matchText = match[0];
        const matchIndex = fullText.indexOf(matchText, startIndex);

        // 遍历文本项以找到匹配项的位置
        let textIndex = 0;
        let found = false;
        for (let i = 0; i < textItems.length; i++) {
            const itemText = textItems[i];
            if (itemText.indexOf(matchText, textIndex) === 0) {
                found = true;
                const quad = quads[i];
                const x = quad[0][0];
                const y = quad[0][1];
                const width = quad[3][0] - x;
                const height = quad[3][1] - y;
                highlights.push({ x, y, width, height });
                textIndex += itemText.length;
                break;
            } else {
                textIndex += itemText.length;
            }
        }
        if (!found) {
            break;
        }

        startIndex = matchIndex + matchText.length;
    }

    // 在canvas上绘制高亮矩形
    for (const highlight of highlights) {
        context.save();
        context.fillStyle = 'rgba(255, 0, 0, 0.5)'; // 红色半透明
        context.fillRect(highlight.x, highlight.y, highlight.width, highlight.height);
        context.restore();
    }
}

// 搜索并高亮关键字
async function highlightKeyword(url) {
    if (url==null) {
        url = '/pdf/成华区安全生产安全指引材料汇编.pdf';
    }
    const keyword = document.getElementById('keyword').value;
    if (!keyword) {
        alert('Please enter a keyword to highlight.');
        return;
    }

    try {
        const pdf = await loadPdf(url);
        const scale = 1.5; // 缩放比例
        const pageNumber = 1; // 要渲染的页码，可以根据需要调整
        await renderPageWithHighlight(pdf, pageNumber, scale, keyword);
    } catch (error) {
        console.error(error);
    }
}